<?php

/**
 * This is the model class for table "brochure".
 *
 * The followings are the available columns in table 'brochure':
 * @property integer $id
 * @property string $name_en
 * @property string $name_th
 * @property string $short_description_en
 * @property string $short_description_th
 * @property string $description_en
 * @property string $description_th
 * @property integer $display_order
 * @property string $file_path 
 * @property string $photo_path
 * @property integer $enable
 * @property integer $active_flag
 * @property string $created_date
 * @property string $updated_date
 * @property string $slug
 */
class Brochures extends CActiveRecord
{
  /**
   * Returns the static model of the specified AR class.
   * @param string $className active record class name.
   * @return Promotion the static model class
   */
  public $randomName;
   
  public static function model($className=__CLASS__)
  {
    return parent::model($className);
  }

  /**
   * @return string the associated database table name
   */
  public function tableName()
  {
    return 'brochures';
  }

  /**
   * @return array validation rules for model attributes.
   */
  public function rules()
  {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
      array('name_en', 'required'),
      array('enable, active_flag', 'numerical', 'integerOnly'=>true),
      array('name_en, name_th, file_path, photo_path, slug', 'length', 'max'=>200),
      array('short_description_en, short_description_th, description_en, description_th, created_date, updated_date', 'safe'),
      // The following rule is used by search().
      // Please remove those attributes that should not be searched.
      array('id, name_en, name_th, short_description_en, short_description_th, description_en, description_th, file_path, photo_path, enable, active_flag, created_date, updated_date, slug', 'safe', 'on'=>'search'),
    );
  }

  /**
   * @return array relational rules.
   */
  public function relations()
  {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
    );
  }

  /**
   * @return array customized attribute labels (name=>label)
   */
  public function attributeLabels()
  {
    return array(
      'id' => 'ID',
      'name_en' => 'Name En',
      'name_th' => 'Name Th',
      'short_description_en' => 'Short Description En',
      'short_description_th' => 'Short Description Th',
      'description_en' => 'Description En',
      'description_th' => 'Description Th',
      'file_path' => 'File Path',
      'photo_path' => 'Photo Path',
      'enable' => 'Enable',
      'active_flag' => 'Active Flag',
      'created_date' => 'Created Date',
      'updated_date' => 'Updated Date',
      'slug' => 'URL',
    );
  }

  /**
   * Retrieves a list of models based on the current search/filter conditions.
   * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
   */
  public function search()
  {
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;

    $criteria->compare('id',$this->id);
    $criteria->compare('name_en',$this->name_en,true);
    $criteria->compare('name_th',$this->name_th,true);
    $criteria->compare('short_description_en',$this->short_description_en,true);
    $criteria->compare('short_description_th',$this->short_description_th,true);
    $criteria->compare('description_en',$this->description_en,true);
    $criteria->compare('description_th',$this->description_th,true);
    $criteria->compare('file_path',$this->file_path,true);
    $criteria->compare('photo_path',$this->photo_path,true);
    $criteria->compare('enable',$this->enable);
    $criteria->compare('active_flag',$this->active_flag);
    $criteria->compare('created_date',$this->created_date,true);
    $criteria->compare('updated_date',$this->updated_date,true);
    $criteria->compare('slug',$this->slug,true);

    return new CActiveDataProvider($this, array(
      'criteria'=>$criteria,
    ));
  }

  public function behaviors(){
    return array(
      'sluggable' => array(
        'class'=>'ext.SluggableBehavior.SluggableBehavior',
        'columns' => array('name_en'),
        'unique' => true,
        'update' => true,
      ),
    );
  }  
  
  public function beforeSave() {
    if ($this->isNewRecord) {
      $this->created_date = new CDbExpression('NOW()');
    }else {
      $this->updated_date = new CDbExpression('NOW()');
    }
    return parent::beforeSave();
  }

  public function getThumbnailPath()
  {
    if (($lastDotPosition = strrpos($this->photo_path, '.')) == true) {
      return substr_replace($this->photo_path, '_t', $lastDotPosition, 0);
    }else {
      return null;
    }
  }

  public function getName()
  {
    $ret = $this->name_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->name_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->name_en;
      }
    }

    return $ret;
  }

  public function getShortDescription()
  {
    $ret = $this->short_description_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->short_description_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->short_description_en;
      }
    }

    return $ret;
  }

  public function getDescription()
  {
    $ret = $this->description_en;

    if (isset($_GET['language'])) {
      switch ($_GET['language']) {
        case "th":
          $data = $this->description_th;
          $ret = (isset($data) && ($data!=''))  ? $data : $ret;
          break;
        default:
          $ret = $this->description_en;
      }
    }

    return $ret;
  }

  public function savePhoto()
  {
  	$this->setRandomName();
    $path = '/uploads/images/brochures/';

    //save image
    $image = CUploadedFile::getInstanceByName('Brochures[photo_path]');

    if (isset($image->name) && $image->saveAs(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name)) {
      //edit file
      $file = Yii::app()->image->load(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name);

      $photoName = $this->randomName;

      $file->resize(263, 148);
      $file->save(Yii::getPathOfAlias('webroot').$path. $photoName.'.jpg');
      unlink(Yii::getPathOfAlias('webroot').'/uploads/_tmp/'.$image->name);
      $ret = $path.$photoName.'.jpg';
      $this->photo_path = $ret;
    }else {
      if (!empty($this->id)) {
        $this->photo_path = $this->findByPk($this->id)->photo_path;
      }else {
        $this->photo_path = null;
      }
    }
    return $this->photo_path;

  }

  function saveFile() {
  	$this->setRandomName();
    $path = '/uploads/files/brochures/';
    $ret = empty($this->file_path) ? null : $this->file_path;
    //save image
    $thumbnail = CUploadedFile::getInstanceByName('Brochures[file_path]');
    if ($thumbnail) {
      switch($thumbnail->type) {
        case 'application/pdf' :
          $type = '.pdf';
        break;
        case 'image/jpeg';
          $type = '.jpg';
        break;
        case 'image/png';
          $type = '.png';
        break;
        case 'image/gif';
          $type = '.gif';
        break;
      }

      if ($thumbnail && $thumbnail->saveAs(Yii::getPathOfAlias('webroot').'/uploads/files/brochures/'.$this->randomName. $type)) {
        $ret =  Yii::app()->request->getBaseUrl(true).$path.$this->randomName. $type;
      }
    }
    return $this->file_path = $ret;
  }
  
  public function setRandomName() {
  	if ($this->randomName==null) {
  		$this->randomName = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789'),0,12);  
		}
  }
 
}